/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.CustomerEntity;
import entity.DataObjectEntity;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;

/**
 *
 * @author wei
 */
@Stateless
public class CustomerEntityFacade extends AbstractFacade<CustomerEntity> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public CustomerEntityFacade() {
        super(CustomerEntity.class);
    }

    public DataModel findCustomer(String userInput, String searchField) {
        Query query = em.createQuery("SELECT C FROM Customer C" + " WHERE C." + "" + searchField + "" + " like " + "'%" + userInput + "%'");
        return new ListDataModel(query.getResultList());
    }

    public DataModel findAllCustomers() {
        Query query = em.createQuery("SELECT C FROM Customer C");
        return new ListDataModel(query.getResultList());
    }

    public DataModel findAllExecutiveCustomers(Long executiveID) {
        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<DataObjectEntity> customerRoot = cq.from(CustomerEntity.class);
        cq.select(customerRoot);
        cq.where(builder.equal(customerRoot.get("customerExecutive").get("id"), executiveID));
        return new ListDataModel(getEntityManager().createQuery(cq).getResultList());
    }

    public DataModel findNoAccountCustomers() {

        CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<DataObjectEntity> customerRoot = cq.from(CustomerEntity.class);
        cq.select(customerRoot);

        cq.where(builder.isNull(customerRoot.get("customerAccount")));
        //cq.where(customerRoot.get("customerAccount").get("createdBy").get("id").isNull());
        System.out.println(cq.toString());
        return new ListDataModel(getEntityManager().createQuery(cq).getResultList());
    }

    public List<CustomerEntity> getLockedUser() {
        Query query = (Query) em.createQuery("Select c from Customer c WHERE c.locked=true");
        List<CustomerEntity> list = (List<CustomerEntity>) query.getResultList();
        return list;
    }
}
